<script setup>
import { nextTick, onBeforeUnmount, onMounted, reactive, ref } from "vue"
import { OlMap } from "@/utils/openlayers"
import { ElMessage } from "element-plus"
import http from "@/utils/http"
import { Close } from "@element-plus/icons-vue"
import DialogDahuaPlayer from '@/components/DialogDahuaPlayer.vue'
import EventComponents from "@/views/map/components/EventComponents.vue"
import formatDate from '@/utils/date'
import RealPath from '@/utils/cy.map.realpath'
import {
    fetchSetMaptZoom,
    fetchMapGrid,
    fetchRemoveMarkerById,
    fetchMapMarker,
    fetchMapZones,
    fetchMarkerById
} from '@/api/map.services'
const emits = defineEmits(['openMarkerDetailDrawer'])
let mapBox = null
const optionsinfo = ref({})
const map_type = ref(null)
/*
 * @description 地图组件
 * @param {*} options
 * @param {*} config
 * @param {*} callback
 */
const init = (options, config, callback) => {
    optionsinfo.value = options
    map_type.value = options.map_type
    mapBox = new OlMap(config.id)
    mapBox.init(options, config, () => {
        callback && callback(mapBox)
    }, config.id)
}

/**
 * @description 添加地图的地图的点击事件
 * @param {*} options
 * @param {*} type
 */
const addMapClick = () => {
    mapBox.clickMarker = mapClickEvent
}
/**
 * @description 加载地图点位
 * @param {*} options
 *  */
const loadMapMarker = async (callback) => {
    const result = await fetchMapMarker(optionsinfo.value.id, 0)
    if (result.code == 1) {
        mapBox.createClusterMarker(result.data.data)
    }
    //地图加载完成在返回一个回调
    callback?.()
}
/**
 * @description 加载地图防区
 * @param {*} options
 * */
const loadMapZones = async () => {
    const result = await fetchMapZones(optionsinfo.value.id)
    if (result.code == 1) {
        mapBox.initDrawZones(result.data, 2)
    }
}
/**
 * @description 加载地图网格
 * @param {*} options
 * */
const loadMapGrid = async () => {
    const result = await fetchMapGrid(optionsinfo.value.id)
    if (result.code == 1) {
        mapBox.createPolygon(result.data)
    }
}
/**
 * @description 重置地图
 * */
const mapReset = () => {
    mapBox.map.getView().setZoom(optionsinfo.value.zoom)
    const center = mapBox.getMapCoordinates(optionsinfo.value)
    mapBox.map.getView().animate({
        center: center,
        duration: 500
    })
}
const mapClickEvent = async (e) => {
    console.log('地图点击事件', e)
    const result = await fetchMarkerById({ id: e.data_.id })
    if (result.code == 1) {
        emits('openMarkerDetailDrawer', result.data)
    }
}
/**
 * @param {*} options
 * @param {*} type
 */
const completeMap = async (callback) => {
    callback && callback()
    // emits('mapLoadCompleted')
    console.log('地图加载完成', callback)
    return
    const marker = optionsinfo.value.marker
    mapBox.createClusterMarker([marker])
    const feature = mapBox.markerLayers[0].feature
    mapBox.map.getView().animate({
        center: feature.getGeometry().getCoordinates(),
        duration: 500
    })
}
/**
 * 根据类型和关键字，筛选需要显示的节点
 * @param {Number[]} types   显示的类型 [1:视频监控,2:公共广播,3:辅助灯光,4:围界防区,5:围界光纤,6:其他设备]
 * @param {String}   keyword 搜索的关键字
 * @param {Function} reset 没有 keyword 时，重置显示的函数
 * @param {Boolean}  visible 根据 keyword 搜索时，是否显示节点
 */
function filterFeature({ subsystem, types, keyword = '', visible = true, visibleAlarm = true }) {
    let featureMap = {}
    for (let key in subsystem) {
        featureMap[key] = []
    }
    let alarmList = []
    let _alarmPointList = {}

    const markerArr = []
    const lineArr = []
    let gridShow = false
    const result = []

    keyword = keyword.trim()

    const reg = keyword ? new RegExp(keyword) : null
    types.forEach(type => {
        markerArr.push(type)
        if (type == 1) {
            lineArr.push(type)
        }
        if (type == 1000) {
            gridShow = true
        }
    })
    if (mapBox.sectorLayers) {
        Object.keys(mapBox.sectorLayers).forEach(key => {
            const layer = mapBox.sectorLayers[key]
            if (types.includes(9)) {
                if (!layer.getVisible()) {
                    layer.setVisible(true)
                }
            } else {
                if (layer.getVisible()) {
                    layer.setVisible(false)
                }
            }
        })
    }
    mapBox.markerLayers.forEach((item, index) => {
        if (!reg) {
            item.feature.setVisibleClose(item.feature)
        }
        item.data.type = 'point'
        if (visibleAlarm && item.data.alarm > 0) {
            _alarmPointList[item.data.device_id] = item.data['alarm']
            alarmList.push(item)
            return
        }

        if (!markerArr.length) {
            return
        }
        if (featureMap[item.data.subsystem_id]) {
            featureMap[item.data.subsystem_id].push(item)
        }
    })
    //搜索防区
    if (lineArr.length) {
        for (let key in mapBox.lineLayers) {
            let lineLayer = mapBox.lineLayers[key]
            const item = {
                layer: lineLayer,
                data: { name: lineLayer.values_.name, id: lineLayer.values_.device_id, type: 'line' }
            }
            if (featureMap[1]) {
                featureMap[1].push(item)
            }
        }
    }

    for (let key in mapBox.Polygonadd) {
        let polygonLayer = mapBox.Polygonadd[key]
        polygonLayer.setVisible(gridShow)
        if (gridShow) {
            const item = {
                layer: polygonLayer,
                data: { name: polygonLayer.values_.name, id: polygonLayer.values_.id, type: 'grid' }
            }
            featureMap[1000].push(item)
        }
    }
    markerArr.forEach(type => {
        featureMap[type]?.forEach(item => {
            if (reg) {
                if (reg.test(item.data.name)) {
                    result.push(item)
                }
                return
            }
            if (!item.data.type || item.data.type == 'point') {
                item.feature.setVisibleOpen(item.feature, item.data)
            }
        })
    })
    if (reg) {
        return result
    }

    alarmList.forEach(item => {
        item.feature.setVisibleOpen(item.feature, item.data)
    })
    setTimeout(() => {
        mapBox.test(_alarmPointList)
    }, 1000)

    featureMap = null

    // 对于线的处理，只能先干掉再通过是否需要显示处理
    Object.keys(mapBox.lineLayers).forEach(key => {
        const layer = mapBox.lineLayers[key]
        mapBox.map.removeLayer(layer)
        !!lineArr.length && mapBox.map.addLayer(layer)
    })
}
/**
 * @description 移动到指定点位
 * @param {Object} feature
 * @param {Object} featureItem
 * @param {Boolean} visibleAlarm
 * */
function moveToFeature(feature, featureItem, visibleAlarm) {
    let center = []
    switch (featureItem.data.type) {
        case 'line':
            center = feature.values_.middleCoordinate
            Object.keys(mapBox.lineLayers).forEach(key => {
                const layer = mapBox.lineLayers[key]
                mapBox.map.removeLayer(layer)
                if (featureItem.data.id == key * 1) {
                    mapBox.map.addLayer(layer)
                }
            })
            break
        case 'grid':
            center = feature.values_.center
            mapBox.Polygonadd.forEach((item, index) => {
                if (feature.values_.id * 1 == item.values_.id * 1) {
                    item.setVisible(true)
                } else {
                    item.setVisible(false)
                }
            })
            break
        default:
            resetKeywordFeature(featureItem.data.id, visibleAlarm)
            center = feature.getGeometry().getCoordinates()
            break
    }
    // resetKeywordFeature(featureItem.data.id, visibleAlarm)
    // // mapBox.map.getView().setZoom(mapBox.map.getView().getMaxZoom())
    // console.log(feature.getGeometry().getCoordinates())
    mapBox.map.getView().animate({
        center: center,
        duration: 500,
    })
}
// 输出组件的方法，让外部组件可以调用
defineExpose({
    init,
    addMapClick,
    loadMapMarker,
    loadMapZones,
    loadMapGrid,
    mapReset,
    filterFeature,
    moveToFeature
})
</script>
<template>
    <div style="position: relative">
        <div style="display: none" class="warning sky-marker-shashuo"></div>
    </div>
</template>
<style lang="scss" scoped>
.sky-marker-shashuo {
    width: 36px;
    height: 36px;
    animation: skyMarkerShashuo 5s infinite;
}

@keyframes skyMarkerShashuo {
    0% {
        box-shadow: 0 0 5px 5px red;
    }

    50% {
        box-shadow: 0 0 5px 5px transparent;
    }

    100% {
        box-shadow: 0 0 5px 5px red;
    }
}
</style>
